package com.rc.evcharger.component;

import com.rc.evcharger.common.enums.SynEnum;
import com.rc.evcharger.redis.RedisService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Create by Yang on 2021/10/14
 */
@Component
public class SynExcution {
    private static Logger logger = LogManager.getLogger(SynExcution.class);
    @Autowired
    private RedisService redisService;

    /**
     * 如果会员在结算中，最多休眠两秒
     *
     * @param memberId
     */
    public String synUpdateOrderCost(Long memberId) {

        long l = System.currentTimeMillis();
        String synKey = SynEnum.SYN_ORDERCOST_MEMBERID.getCode() + memberId;


        for (int i = 0; i < 20; i++) {
            //保证原子性
            if (!redisService.setIfAbsent(synKey, String.valueOf(l), 2000L)) {
                logger.info("synIfAbsent会员ID：{}在结算中!!,请耐心等待", memberId);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                continue;
            } else {
                break;
            }
        }
        logger.info("synUpdateOrderCost方法,会员ID：{}执行时间：{}毫秒", memberId, System.currentTimeMillis() - l);
        return String.valueOf(l);
    }


    /**
     * @param orderNum
     */
    public int synOrderNum(String key, Long time) {
        if (!redisService.setIfAbsent(key, 1, time)) {
            logger.warn("chargeBalace.A6.2秒内重复结算,已返回，对应订单号:" + key);
            return 0;
        }
        return 1;
    }

    /**
     * @param memberId
     */
    public int synOrderMemberId(String key, Long time) {
        if (!redisService.setIfAbsent(key, 1, time)) {
            logger.warn("chargeBalace.A6.2秒内重复结算,已返回，对应订单号:" + key);
            return 0;
        }
        return 1;
    }


}
